package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishMapper;
import com.sky.service.IDishFlavorService;
import com.sky.service.IDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Autowired
    private IDishFlavorService iDishFlavorService;

    @Override
    @Transactional
    public void addDishAndFlavor(DishDTO dishDTO) {
        //存储  dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setId(null);
        this.save(dish);
        //存储 Flavor
        DishFlavor dishFlavor = new DishFlavor();
        List<DishFlavor> flavors = dishDTO.getFlavors();

        flavors.forEach(s->{
            s.setId(null);
            s.setDishId(dish.getId());
        });
        iDishFlavorService.saveBatch(flavors);
    }

    @Override
    @Transactional
    public void updateDishAndFlavor(DishDTO dishDTO) {
        //
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        this.updateById(dish);
        //  修改 Flavor
        List<DishFlavor> flavors = dishDTO.getFlavors();
            //删除
        LambdaQueryWrapper<DishFlavor> lqw =new LambdaQueryWrapper<>();
        lqw.in(DishFlavor::getDishId,dish.getId());
        iDishFlavorService.remove(lqw);
            //添加
        flavors.forEach(s->{ s.setId(null);s.setDishId(dish.getId());});
        iDishFlavorService.saveBatch(flavors);
    }
}
